package com.ts.main.mini.config;

import com.ts.main.mini.constants.RedisPrefixConstants;
import com.ts.main.mini.utils.RedisUtil;
import com.ts.main.mini.utils.JwtTokenUtil;
import com.ts.main.mini.context.UserContext;
import com.ts.main.mini.exception.CommonException;
import com.ts.main.mini.exception.EmError;
import com.ts.main.mini.vo.UserVo;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

/**
 * @Author:lk
 * @Date: 2025/5/15  00:20
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    private final PathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 方法执行前预处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行路径
        String requestURI = request.getRequestURI();
        for (String path : ExcludePaths.EXCLUDE_AUTH) {
            if (pathMatcher.match(path, requestURI)) {
                return true;
            }
        }
        // 解析token
        String token = request.getHeader("token");
        if (Objects.isNull(token)) {
            throw new CommonException(EmError.AUTH_TOKEN_EXPIRED);
        }
        String phone = JwtTokenUtil.validateToken(token);
        if (Objects.isNull(phone)) {
            throw new CommonException(EmError.AUTH_TOKEN_EXPIRED);
        }
        // 获取用户缓存信息
        UserVo userVo = (UserVo) redisUtil.getObject(RedisPrefixConstants.USER_INFO + phone);
        if (Objects.isNull(userVo)) {
            throw new CommonException(EmError.AUTH_TOKEN_EXPIRED);
        }
        // 用户是否被禁用
        if (userVo.getIsBlocked()) {
            throw new CommonException(EmError.AUTH_USER_IS_BLOCK_LOGIN);
        }
        // 存入UserContext
        UserContext.setUser(userVo);
        return true;
    }

    /**
     * 方法执行后
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
    }

    /**
     * 页面渲染后
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                @Nullable Exception ex) throws Exception {

    }

}
